apiRoot = "/api/"
S.apiRoot = apiRoot
S.fileRoot = "/r/"

api = {}
S.api = api

AjaxOption = (type, data, settings) ->
    @type = type

    if type == "POST" || type == "PUT" || type == "DELETE"
        @data = data && JSON.stringify(data)
        @contentType = "application/json"
    else
        @data = data

    @cache = false; # !!!

    _.extend(this, settings) if settings?

fail = (jqxhr)->
    if jqxhr.status == 401
        S.showSignInDialog()
    else
        Promise.reject jqxhr

api.get = (relativeUrl, data, settings) ->
    q = Promise.resolve $.ajax(S.apiRoot + relativeUrl, new AjaxOption("GET", data, settings))
    q.catch fail

api.getAbsolute = (absoluteUrl, data, settings) ->
    q = Promise.resolve $.ajax(absoluteUrl, new AjaxOption("GET", data, settings))
    q.catch fail

api.post = (relativeUrl, data, settings) ->
    q = Promise.resolve $.ajax(S.apiRoot + relativeUrl, new AjaxOption("POST", data, settings))
    q.catch fail

api.put = (relativeUrl, data) ->
    q = Promise.resolve $.ajax(S.apiRoot + relativeUrl, new AjaxOption("PUT", data))
    q.catch fail

api.remove = (relativeUrl, data) ->
    q = Promise.resolve $.ajax(S.apiRoot + relativeUrl, new AjaxOption("DELETE", data))
    q.catch fail

S.upload5callback = ($file, progressCallback)->
    files = $file[0].files
    return unless files && files.length

    uploadOneFile = (file, index)->
        file = files[index]
        xhr = new XMLHttpRequest()
        xhr.open "POST", apiRoot + "upload5"
        data = new FormData()
        data.append("f0", file)
        xhr.send data

        xhr.onload = (e)->
            finishCount++
            if xhr.status != 200
                progressCallback index, files.length, false, e
            else
                response = xhr.responseText && JSON.parse xhr.responseText
                progressCallback index, files.length, true, response.f0.path

        xhr.onerror = (e)->
            finishCount++
            progressCallback index, files.length, false, e

    finishCount = 0
    uploadOneFile file, index for file, index in files

